from sqlalchemy.orm import sessionmaker

from api.models.api_models import Video


class VideoDAO:
    def __init__(self, engine):
        self.engine = engine
        self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)

    def create(self, video_id, user_id, video_type, video_file_path, upload_time=None):
        session = self.Session()
        video = Video(video_id=video_id, user_id=user_id, video_type=video_type, video_file_path=video_file_path, upload_time=upload_time)
        session.add(video)
        session.commit()
        session.close()
        return video

    def read(self, video_id):
        session = self.Session()
        video = session.query(Video).filter_by(video_id=video_id).first()
        session.close()
        return video

    def update(self, video_id, user_id=None, video_type=None, video_file_path=None, upload_time=None):
        session = self.Session()
        video = session.query(Video).filter_by(video_id=video_id).first()
        if user_id is not None:
            video.user_id = user_id
        if video_type is not None:
            video.video_type = video_type
        if video_file_path is not None:
            video.video_file_path = video_file_path
        if upload_time is not None:
            video.upload_time = upload_time
        session.commit()
        session.close()

    def delete(self, video_id):
        session = self.Session()
        video = session.query(Video).filter_by(video_id=video_id).first()
        session.delete(video)
        session.commit()
        session.close()